package com.zs.toolbox.web2j.system.message.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.zs.toolbox.web2j.system.message.controller.WtMessageController;
import com.zs.toolbox.web2j.system.message.domain.request.WtSendEmailRequest;
import com.zs.toolbox.web2j.system.message.domain.request.WxSendSmsVcodeRequest;
import com.zs.toolbox.web2j.system.message.mq.WtMessageTagConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.starter.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.starter.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RocketMQMessageListener(topic = "${message.queue.rocketmq.topic}", selectorExpress = "*", consumerGroup = "${message.queue.rocketmq.group}")
public class MessageExtConsumer implements RocketMQListener<MessageExt> {

    @Value("${message.queue.rocketmq.group}")
    String consumerGroup;

    @Value("${message.queue.rocketmq.topic}")
    String consumerTopic;

    @Autowired
    WtMessageController wtMessageController;

    @Override
    public void onMessage(MessageExt msg) {
        try {
            switch (msg.getTags()) {
                case WtMessageTagConst.MESSSAGE_TAG_EMAIL:
                    WtSendEmailRequest request = JSON.parseObject(msg.getBody(), WtSendEmailRequest.class);
                    request.setIsSync(true);
                    wtMessageController.sendEmail(request);
                    break;
                case WtMessageTagConst.MESSSAGE_TAG_SMS_LOGIN:
                    wtMessageController.sendPhoneLoginVCodeSms(JSON.parseObject(msg.getBody(), WxSendSmsVcodeRequest.class));
                    break;
                case WtMessageTagConst.MESSSAGE_TAG_SMS_REGISTER:
                    wtMessageController.sendPhoneRegisterVCodeSms(JSON.parseObject(msg.getBody(), WxSendSmsVcodeRequest.class));
                    break;
                case WtMessageTagConst.MESSSAGE_TAG_SMS_FINDPASSWORD:
                    wtMessageController.sendPhoneFindPasswordVCodeSms(JSON.parseObject(msg.getBody(), WxSendSmsVcodeRequest.class));
                    break;
            }
        } catch (Exception e) {
            log.warn(String.format("conumer message{} error", msg), e);
        } finally {
            log.debug("message consumer rocketmq group<{}> start finish [ok]", consumerGroup);
        }
    }
}
